package org.example.service.impl;

import cn.hutool.crypto.digest.DigestUtil;
import org.example.dto.ShoppingUser;
import org.example.dto.Token;
import org.example.manage.ShoppingUserManage;
import org.example.mapper.ShoppingUserMapper;
import org.example.rvo.ResultVO;
import org.example.service.ShoppingUserService;
import org.example.util.JWTUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

@Service
public class ShoppingUserServiceImpl implements ShoppingUserService {
    private final String PREFIX_KEY = "prefix:login:user:";
    private final String SUFFIX_KEY = "suffix:login:user:";

    @Resource
    private ShoppingUserManage shoppingUserManage;

    @Resource
    private ShoppingUserMapper shoppingUserMapper;

    @Override
    public ResultVO login(String name, String pass) throws Exception {
        ShoppingUser shoppingUser = shoppingUserMapper.queryUserByName(name);
        if(shoppingUser == null){
            return  ResultVO.failure("500","用户名不存在");
        }else{
            String id =shoppingUser.getId();
            //先去从redis读取看一下是否存在redis对应的key，如果有代表无需登录
            String suffixToken = shoppingUserManage.getToken(SUFFIX_KEY + id);
            String prefixToken = shoppingUserManage.getToken(PREFIX_KEY + id);
            if(suffixToken != null && prefixToken != null){
          //      Token token = new Token(suffixToken,prefixToken);
                return ResultVO.success("200","token未过期，无需二次登录",suffixToken);
            }
            if(suffixToken != null && prefixToken == null){
                return ResultVO.failure("500","token过期，请重新登录");
            }
            //token为null
            pass = DigestUtil.md5Hex(DigestUtil.md5Hex(pass)+shoppingUser.getUserSalt());
            ShoppingUser user = shoppingUserMapper.queryUserByNameAndPass(name, pass);
            if(user != null){
                suffixToken = JWTUtil.createJWT(user.getId(),user,"login",30*60*1000L);
                //添加到redis中，时间和jwt一致
                shoppingUserManage.addToken(SUFFIX_KEY + id,suffixToken,30*60L);
                shoppingUserManage.addToken(PREFIX_KEY+id, UUID.randomUUID().toString().replaceAll("-",""),1500L);
               // Token token = new Token(suffixToken,prefixToken);
                return ResultVO.success("200","登录成功",suffixToken);
            }
            return ResultVO.failure("500","密码或用户错误");
        }
    }

    @Override
    public ResultVO queryMySelf(String id) throws Exception {
        ShoppingUser user = shoppingUserMapper.queryUserById(id);
        user.setUserPass("PROTECTED");
        return ResultVO.success("200","查询用户信息成功",user);
    }
}
